package spring.aop.test;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import sun.misc.ProxyGenerator;

public class MyIh implements InvocationHandler {

    private Object proxyObj; // 被代理对象
    private Object proxy; // 代理对象

    public MyIh(Object obj) {
        this.proxyObj = obj;
    }

    public Object getInstance() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                proxyObj.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        @SuppressWarnings("restriction")
        byte[]  b= ProxyGenerator.generateProxyClass(proxy.getClass().getSimpleName(),proxy.getClass().getInterfaces());
        FileOutputStream out = new FileOutputStream("./"+proxy.getClass().getSimpleName()+".class");
        out.write(b);
        out.flush();
        out.close();

        System.out.println("invoke begin");
        Object result = method.invoke(proxyObj, args);
        System.out.println("invoke end");
        System.out.println(proxy.getClass().getName());
        this.proxy = proxy;
        return result;
    }

    public static void main(String[] args) {
        IServiceA sa = new ServiceA("tlx");
        MyIh ih = new MyIh(sa);
        IServiceA serviceA = (IServiceA) ih.getInstance();
        //代理对象只能执行父接口中定义过的方法，不能使用ServiceA接受代理对象
        serviceA.say(999);
        System.out.println(serviceA == ih.proxy);
    }

}
